<?php

namespace App\Console\Commands;

use EasyWeChat\Factory;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class Template extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'template:send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '发送模板消息';

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        $redPackets = $this->getRedPackets();
        $config = [
            'app_id' => env('WECHAT_RED_PACKET_APPID'),
            'secret' => env('WECHAT_RED_PACKET_APPKEY'),
            'log' => [
                'level' => 'debug',
                'permission' => 0777,
                'file' => storage_path('logs/easywechat_' . date('Ymd') . '.log'),
            ],
        ];
        $templateId = env('WECHAT_RED_PACKET_TPL_ID');
        $userCenter = env('USER_CENTER_URL', 'https://user.xingchengfu.com/mid');
        $wechatApp = Factory::officialAccount($config);

        foreach (array_chunk($redPackets, 200, true) as $chunks) {
            $userLst = $this->getUserInfoBatch(array_keys($chunks));
            // 仅抓取关注了此公众号的用户
            foreach ($userLst as $user) {
                $redPacket = $redPackets[$user->user_id];
                $msg = [
                    'touser' => $user->oid,
                    'template_id' => $templateId,
                    'url' => $userCenter,
                    'data' => [
                        'first' => '尊敬的客户，您好，您的账户积分变更如下:',
                        'FieldName' => '结算日期',
                        'Account' => date('m-d 23:59:59', strtotime('-1 day')),
                        'change' => '增加',
                        'CreditChange' => ['value' => $redPacket['integral'], 'color' => '#ff3300'],
                        'CreditTotal' => intval($user->total),
                        'Remark' => ['value' => '点击查看积分详情', 'color' => '#006699']
                    ],
                ];
                $wechatApp->template_message->send($msg);
            }
        }
    }

    /**
     * 批量获取用户信息.
     *
     * @param array $userIds 通过userId获取到在`红包来了`这个公众号的信息
     *
     * @return mixed|null
     */
    protected function getUserInfoBatch(array $userIds)
    {
        $users = DB::table(env('DB_DATABASE_USER', '') . 'wx_user')
            ->join('template_user', 'wx_user.unionid', '=', 'template_user.unionid')
            ->join('user', 'user.user_id', '=', 'wx_user.user_id')
            ->whereIn('user.user_id', $userIds)
            ->groupBy('user_id')
            ->select(['template_user.wx_openid as oid', DB::raw('sum(total_amount) as total'), 'template_user.nickname', 'user.user_id'])
            ->get();
        return $users ?? [];
    }

    /**
     * 获取用户前一天的红包信息,从Redis缓存中读取前一天的红包积分流水，然后group by userId.求和
     *
     * @return array 每一个元素都是 userId => ['integral' => '积分', 'history' => '余额']
     */
    protected function getRedPackets()
    {
        $redPacketsFlow = Cache::get('Template_Message', []);
        $defaultInfo = [
            'integral' => 0,
            'history' => 0,
            'status' => 'success',
        ];
        $redPackets = array_reduce($redPacketsFlow, function (array $accumulator, array $element) use ($defaultInfo) {
            // 仅成功的时候做处理
            if ($element['status'] !== 'success') {
                return $accumulator;
            }
            $userId = $element['user_id'];
            $record = $accumulator[$userId] ?? $defaultInfo;
            $accumulator[$userId] = [
                'history' => max($record['history'], $element['history']),
                'integral' => $record['integral'] + $element['integral'],
            ];

            return $accumulator;
        }, []);

        return $redPackets;
    }
}
